package com.software.frontend.loginAndRegist;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.software.frontend.MainActivity;
import com.software.frontend.R;
import com.software.frontend.loginAndRegist.entity.UserExtends;
import com.software.frontend.loginAndRegist.utils.Result;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginByPhoneAndPasswordActivity extends AppCompatActivity {

    TextView textSelectPhoneLocation, toLoginByPhoneAndVarificationPage;
    Spinner spinnerSelectPhoneLocation;
    ImageView imgPasswordIcon;
    EditText phone, password;
    Button sure;
    String[] phoneLocations;
    OkHttpClient okHttpClient = new OkHttpClient();
    Result result;
    private static final String serviceLocation = "login/loginByPhoneNumberAndPassword";
    private static final Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_by_phone_and_password);

        staticDataInit();

        initViews();

        setListneners();
    }

    private void staticDataInit() {
        phoneLocations = getResources().getStringArray(R.array.Phone_location_number);
    }


    private void initViews() {
        textSelectPhoneLocation = (TextView) findViewById(R.id.text_select_phone_location);
        spinnerSelectPhoneLocation = (Spinner) findViewById(R.id.spinner_select_phone_location);
        imgPasswordIcon = (ImageView) findViewById(R.id.img_password_icon);
        phone = (EditText) findViewById(R.id.editTextPhone);
        password = (EditText) findViewById(R.id.editTextTextPassword);
        //默认这是密码不可见
        password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        sure = (Button) findViewById(R.id.login_by_phone_and_Password_sure);

        toLoginByPhoneAndVarificationPage = (TextView) findViewById(R.id.text_to_login_by_varification);


    }

    private void setListneners() {

        //电话属地选择监听
        spinnerSelectPhoneLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (phoneLocations[position].equals("...")){
                    Toast.makeText(LoginByPhoneAndPasswordActivity.this, "更多地区正在交洽...", Toast.LENGTH_SHORT).show();
                }else{
                    textSelectPhoneLocation.setText(phoneLocations[position]);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //密码可见性监听
        imgPasswordIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (password.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD){
                    imgPasswordIcon.setImageResource(R.drawable.login_password_icon_unsee);
                    password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }else {
                    imgPasswordIcon.setImageResource(R.drawable.login_password_icon_see);
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
            }
        });

        //登陆按钮监听
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (phone.getText().toString().length()!=11){
                    Toast.makeText(LoginByPhoneAndPasswordActivity.this, "请输入11位电话号", Toast.LENGTH_SHORT).show();
                }else if (password.getText().toString().equals("")){
                    Toast.makeText(LoginByPhoneAndPasswordActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    FormBody formBody = new FormBody.Builder()
                            .add("phoneNumber", phone.getText().toString())
                            .add("password", password.getText().toString())
                            .build();
                    Request request = new Request.Builder().url(getResources().getString(R.string.localhost) + serviceLocation).post(formBody).build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            Log.i("onFailure" , "访问失败");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String s = response.body().string();
                            result = gson.fromJson(s, new TypeToken<Result<UserExtends>>(){}.getType());
                            if (result.getCode() == 200){
                                Intent intent = new Intent(LoginByPhoneAndPasswordActivity.this, MainActivity.class);
                                UserExtends userExtends = (UserExtends) (result.getData().get(0));
                                intent.putExtra("usersExtends", userExtends);
                                startActivity(intent);
                                finish();
                            }else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(LoginByPhoneAndPasswordActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }

            }
        });


        //跳转验证码登陆按钮监听
        toLoginByPhoneAndVarificationPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent switchLoginMethod = new Intent(LoginByPhoneAndPasswordActivity.this, LoginAndRegisterByPhoneForVerificationCodeActivity.class);
                startActivity(switchLoginMethod);
            }
        });

    }


}